#include <cstdio>
#include <cstdlib>
#include <strings.h>
#include <unistd.h>
#include <sys/timerfd.h>
#include <iostream>

int main()
{
    // int timerfd_create(int clockid, int flags);
    // CLOCK_MONOTONIC 以机器启动时的时间为基准，关心相对时间
    // flags 0 设置阻塞
    int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
    if (timerfd < 0) {
        perror("timerfd_create err");
        exit(-1);
    }

    // int timerfd_settime(int fd, int flags, 
    //    const struct itimerspec *new_value,
    //    struct itimerspec *old_value);
    // flags 默认设为0 使用相对时间
    struct itimerspec timerspec;
    bzero(&timerspec, sizeof(timerspec));
    timerspec.it_value.tv_sec = 1; //设置第一次超时时间
    timerspec.it_interval.tv_sec = 1; //设置后续超时时间
    if(timerfd_settime(timerfd, 0, &timerspec, nullptr) < 0) {
        perror("timerfd_settime err");
        exit(-1);
    }
    
    while (true)
    {
        sleep(3);
        uint64_t times;
        int ret = read(timerfd, &times, 8);
        if(ret < 0) {
            perror("read err");
            exit(-1);
        }
        std::cout << "超时, 定时器fd: " << timerfd << " ,距离上次检测超时 " << times << " 次" << std::endl;
    }
    close(timerfd);
    return 0;
}

